//
//  ZGoodsSearchViewController.m
//  shopSN
//
//  Created by yisu on 16/6/29.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZGoodsSearchViewController.h"
#import "ZCommonGoodsInfoViewController.h"//会员商品信息页面


//子视图
#import "ZGoodsCell.h"
#import "ZSearchHeader.h"

@interface ZGoodsSearchViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITextFieldDelegate>
{
    UIView *bgView;        //背景视图
    UITextField *searchTF; //搜索文本框
    
    UICollectionView *searchListColletionView;//主视图部分-顶部视图
    
    
    NSMutableArray *_searchDataArray;//搜索结果存储数组
    NSArray *_currentDataArray;//当前数据
    int _currentPage;//页数
    
}



@end

@implementation ZGoodsSearchViewController


- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    //self.tabBarController.tabBar.hidden =YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = NO;
    //self.tabBarController.tabBar.hidden =NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始 数据
    _currentPage = 1;
    _searchDataArray = [NSMutableArray array];
    
    [self initNavi];// 自定义导航栏
    
    [self getData];//获取数据
    
    [self initMainView];//初始化主页面视图
    
    
}


#pragma mark ===== 获取数据 =====
- (void)getData {
    
    
    
    
    if (self.isGoods) {
        
        //搜索会员商品
        [self goodsSearchRequest:self.searchStr andPageNum:_currentPage];
        
        
    }else{
        
        //搜索会员旅游
        [self tourismSearchRequest:self.searchStr andPgeNum:_currentPage];
    }
    
    
}

#pragma mark - goodsSearch
- (void)goodsSearchRequest:(NSString *)searchName andPageNum:(int)pageNum {
    //NSLog(@"goods search:%@",searchName);
    if (_currentPage == 0) {
        _currentPage = 1;
    }
    
    //115.159.146.202/api/home.php?action=goods_search&title=婴儿&Page=1&pagesize=10&format=json
//    NSString *page = [NSString stringWithFormat:@"%d",pageNum];
//    NSString *pageSize = @"10";
//    NSDictionary *params = @{@"title":searchName,
//                             @"page":page,
//                             @"pagesize":pageSize};
    [ZHttpRequestService GETHome:@"Search" withParameters:@{@"title":searchName} success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            [SXLoadingView hideProgressHUD];
            if (IsNull(jsonDic[@"data"])) {
                [SXLoadingView showAlertHUD:@"数据为空" duration:1.5];
                return ;
            }
            NSArray *array = [Parse parseGoodsSearchData:jsonDic[@"data"]];
            //NSLog(@"dataArray:%@",array);
            _currentDataArray = array;
            [_searchDataArray addObjectsFromArray:array];
            [searchListColletionView reloadData];
            
        }else{
            NSString *message = jsonDic[@"message"];
            [SXLoadingView showAlertHUD:message duration:SXLoadingTime];
            _currentPage--;
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"请求失败" duration:SXLoadingTime];
        _currentPage--;
    } animated:NO withView:nil];
    
    
}


#pragma mark - tourismSearch
- (void)tourismSearchRequest:(NSString *)searchName andPgeNum:(int)pageNum  {
    if (_currentPage == 0) {
        _currentPage = 1;
    }
    //NSLog(@"tourism search:%@",searchName);
    //115.159.146.202/api/home.php?action=lvyou_search&title=国&format=json
    NSString *page = [NSString stringWithFormat:@"%d",pageNum];
    NSString *pageSize = @"10";
    NSDictionary *params = @{@"title":searchName,
                             @"page":page,
                             @"pagesize":pageSize};
    [ZHttpRequestService GETHome:@"lvyou_search" withParameters:params success:^(id responseObject, BOOL succe, NSDictionary *jsonDic) {
        if (succe) {
            NSArray *array = [Parse parseTourismSearchData:jsonDic[@"data"]];
            //NSLog(@"dataArray:%@",array);
            _currentDataArray = array;
            [_searchDataArray addObjectsFromArray:array];
            [searchListColletionView reloadData];
            
            
        }else{
//            NSString *message = jsonDic[@"message"];
//            [SXLoadingView showAlertHUD:message duration:SXLoadingTime];
            NSLog(@"搜索失败，显示header");
            _currentPage--;
        }
    } failure:^(NSError *error) {
        [SXLoadingView showAlertHUD:@"请求失败" duration:SXLoadingTime];
        _currentPage--;
    } animated:NO withView:nil];
}





#pragma mark - ===== 页面设置 =====
#pragma mark - 自定义导航栏
// 自定义导航栏
- (void)initNavi {
    
    BaseView *topView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, __kWidth, 64)];
    topView.backgroundColor = HEXCOLOR(0xffffff);
    [self.view addSubview:topView];
    
    
    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 25, __kWidth, 40)];
    //subView.backgroundColor = __DefaultColor;
    [topView addSubview:subView];
    
    
    
    //左侧分类 按钮
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 10, 20, 20)];
    //backBtn.backgroundColor = __TestOColor;
    [backBtn setBackgroundImage:MImage(@"fanhui.png") forState:BtnNormal];
    [backBtn addTarget:self action:@selector(backAciton) forControlEvents:BtnTouchUpInside];
    [subView addSubview:backBtn];
    
    
    
    
    //中间搜索框
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(CGRectXW(backBtn)+15, 5, CGRectW(subView)-CGRectW(backBtn)-30-45, 30)];
    searchView.layer.borderWidth = 1;
    searchView.layer.borderColor = HEXCOLOR(0xdedede).CGColor;
    searchView.backgroundColor = HEXCOLOR(0xffffff);
    searchView.layer.cornerRadius = 5;
    [subView addSubview:searchView];
    [self createSearchSubView:searchView];
    

}




//自定义 搜索视图 内部控件
- (void)createSearchSubView:(UIView *)btnView {
    
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7.5, 15, 15)];
    imageView.image = MImage(@"sousuo");
    //imageView.backgroundColor = __TestOColor;
    [btnView addSubview:imageView];
    

    searchTF = [[UITextField alloc] initWithFrame:CGRectMake(CGRectXW(imageView)+5, 5, (CGRectW(btnView)-CGRectW(imageView)-20), CGRectH(btnView)-10)];
    //searchTF.backgroundColor = __TestOColor;
    searchTF.font = MFont(14);
    searchTF.textColor = HEXCOLOR(0x333333);
    
    [searchTF setReturnKeyType:UIReturnKeySearch];
    searchTF.clearButtonMode = UITextFieldViewModeWhileEditing;//清除按钮样式
    searchTF.delegate = self;
    [btnView addSubview:searchTF];
    
    if (IsNilString(_searchStr)) {
        searchTF.placeholder = @"商品搜索";
    }else {
        searchTF.placeholder = _searchStr;
    }
    
    
}

#pragma mark - 初始化 主视图
//初始化 主视图
- (void)initMainView {
    //背景图 color (240 240 240)   (f0f0f0)
    bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, __kWidth, __kHeight-64)];
    bgView.backgroundColor = HEXCOLOR(0xffffff);
    [self.view addSubview:bgView];
    
    
    
    //商品列表视图
    CGRect frame = CGRectMake(0, 0, CGRectW(bgView), CGRectH(bgView)-50);
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    searchListColletionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    searchListColletionView.backgroundColor = HEXCOLOR(0xf0f0f0);
    searchListColletionView.dataSource = self;
    searchListColletionView.delegate   = self;
    [bgView addSubview:searchListColletionView];

    
    //1 注册cell
    [searchListColletionView registerClass:[ZGoodsCell class] forCellWithReuseIdentifier:@"GoodsCell"];
    //2 header
    [searchListColletionView registerClass:[ZSearchHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
    
    
    
    
    //刷新控件
    //[searchListColletionView addHeaderWithTarget:self action:@selector(refreshGoodsData)];//下拉刷新
    [searchListColletionView addFooterWithTarget:self action:@selector(loadMoreGoodsData)];//上拉加载更多
    
    
}

- (void)mainTopViewAddSubView:(UIView *)view {
    UIImageView *topIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectW(view), 1)];
    topIV.backgroundColor = HEXCOLOR(0xdedede);
    [view addSubview:topIV];
    
    UIImageView *bottomIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectH(view)-1, CGRectW(view), 1)];
    bottomIV.backgroundColor = HEXCOLOR(0xdedede);
    [view addSubview:bottomIV];
    
    
}

#pragma mark - ===== 按钮方法 =====

//导航栏左侧 返回按钮 触发方法
- (void)backAciton {
    NSLog(@"返回前页面");
    
    if (self.navigationController.viewControllers.count>1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}


#pragma mark - searchTF Delegate
//确认搜索框输入内容
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSString *searchStr = textField.text;
    if (searchStr.length == 0) {
        NSLog(@"没有输入内容");
    }else {
        
        [self sendRequestWithString:textField.text];
    }
    
    [textField resignFirstResponder];
    
    return YES;
}

//发送搜索请求
- (void)sendRequestWithString:(NSString *)searchStr {
    //测试
    NSLog(@"输入搜索内容为:%@",searchStr);
    self.searchStr = searchStr;
    
    //初始化 数据
    _currentPage = 1;
    [_searchDataArray removeAllObjects];
    //发送搜索请求
    [self getData];
    
    //刷新collection
    //[searchListColletionView reloadData];
}




#pragma mark - goodsListCollectionView DataSource and Delegate
//每组 多少items
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //return 6;
    return _searchDataArray.count;
}

//Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZGoodsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GoodsCell" forIndexPath:indexPath];
    
    //    NSLog(@"x:%f===%f",cell.frame.origin.x, cell.frame.origin.y);
    //    NSLog(@"w:%f===h:%f",cell.frame.size.width, cell.frame.size.height);
    
    
    ZGoodsModel *goods = [[ZGoodsModel alloc] init];
    goods = _searchDataArray[indexPath.row];
    
    cell.gl_descLb.text = goods.goodsTitle;
    //cell.gl_pricesLb.text = goods.goodsNowPrice;
    cell.gl_pricesLb.text = [NSString stringWithFormat:@"￥%@",goods.goodsNowPrice];
    cell.gl_salesLb.hidden = YES;
    NSString *picUrl = [NSString stringWithFormat:@"%@%@",GoodsImageUrl, goods.goodsPicUrl];
    [cell.gl_goodsIV sd_setImageWithURL:[NSURL URLWithString:picUrl] placeholderImage:MImage(@"zp_k.png")];
    
    return cell;
}

//header和footer
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        ZSearchHeader *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header" forIndexPath:indexPath];
        //_topLb.text    = @"亲，“雷logo过…”暂无搜索结果。您是不是要搜：";
        
        headerView.topLb.text = [NSString stringWithFormat:@"亲，“%@” 暂无搜索结果，请重新输入搜索内容。",self.searchStr];
        [self setLabeltextAttributes:headerView.topLb];
        reusableView = headerView;
        
        
    }
    return reusableView;
}



//内容距离屏幕边缘的距离 参数顺序是top,left,bottom,right
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    return UIEdgeInsetsMake(5.0f, 0, 5.0f, 0);
    
}

//x 间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

//y 间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}


//item 宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //横向2 纵向3
    return CGSizeMake((CGRectW(searchListColletionView)-2)/2-5/2, CGRectW(searchListColletionView)/2+100);
    
    //单行显示
//    return CGSizeMake(CGRectW(searchListColletionView), CGRectW(searchListColletionView)-50);
    
}

//Header Footer 宽高  ***高度 135改为125
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (!_searchDataArray) {
//        return CGSizeMake(CGRectW(searchListColletionView), 125);
        return CGSizeMake(CGRectW(searchListColletionView), 100);
    }
    
    return CGSizeZero;
}

//footer 宽高
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
//    return CGSizeMake(CGRectW(searchListColletionView), 5);
//}



//选中触发方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"选择的是: 第%ld组 第%ld个",(long)indexPath.section, (long)indexPath.row);
    
    ZGoodsModel *goods = [[ZGoodsModel alloc] init];
    goods = _searchDataArray[indexPath.row];
    
    if (_isGoods) {
        //跳转至会员商品信息页面
        ZCommonGoodsInfoViewController *vc = [[ZCommonGoodsInfoViewController alloc] init];
        vc.comGoodsID = goods.goodsID;
        NSLog(@"选择商品:%@===>进入普通商品信息页面", goods.goodsTitle);
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}




//设置Label文字指定位置大小 颜色
- (void)setLabeltextAttributes:(UILabel *)label {
    NSString *text = label.text;
    
    NSUInteger length = [self.searchStr length];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:text];
    
    //搜索内容 字符颜色
    [attri addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x333333) range:NSMakeRange(3, length)];
    [label setAttributedText:attri];
    
}


#pragma mark - ===== 刷新控件设置内容 =====
#pragma mark - 上拉加载更多
- (void)collectionViewFootLoadAction {
    
    [self loadMoreGoodsData];
}


//加载更多商品
- (void)loadMoreGoodsData {
    NSLog(@"商品搜索页面 加载更多");
    [searchListColletionView footerEndRefreshing];
    if (_currentDataArray.count == 10) {
        _currentPage++;
        [self getData];
    }else{
        searchListColletionView.footerRefreshingText = @"没有更多数据了 ...";
        searchListColletionView.footerReleaseToRefreshText = @"没有更多数据了 ...";
    }
    
    
    
}


#pragma mark - 下拉刷新数据
- (void)refreshGoodsData {
    NSLog(@"商品搜索页面 下拉刷新");
    [searchListColletionView headerEndRefreshing];
    //初始化 数据
    _currentPage = 1;
    [_searchDataArray removeAllObjects];
    [self getData];
}


#pragma mark - others
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
